/**
 * desc: 模糊查询商品公共组件
 * @ width: {string} 宽度  默认160
 * @ value: {string} 商品id  用于回显已经选中的数据
 * @ goodsId: {string} 供应商id  必传
 * @ goodsName: {string} 供应商id  必传
 * @ onChange: {func} 选择项发生变化时的事件 必传
 * @ index: {number} 如果是在表格中，把下标返回
 * @ type: {string} 查询维度：spu【goodsCommonId】 sku【goodsId】
 *
 */

import React from 'react';
import { Popover, Input, Tooltip, Select } from 'antd';
import { find } from 'lodash';
import { queryCommonGoodsList, queryGoodsList } from '@/services/common';
import { customTrimFunc } from '@/utils/utils.jsx';

const { Option } = Select;
export default class FuzzyQueryGoods extends React.PureComponent {

  constructor(props){
    super(props);
    this.state  = {
      data: [],
      visible: 1,
      loading: false,
      goodsId: props.value,
      inputVal: props.goodsName,
    }

    this.inputEl = React.createRef();
    this.timeout = null;
  }

  componentDidMount() {
    const { goodsName } = this.props;
    if(goodsName) {
      this.handleSearch(goodsName);
    }
  }

  fetch = (value, callback) => {
    if (this.timeout) {
      clearTimeout(this.timeout);
      this.timeout = null;
    }
    const { storeId, type='sku' } = this.props;

    const fake = async () => {
      let res;
      //去除空格
      const newParams = customTrimFunc({
        storeId,
        goodsName: value,
        size: 50,
        current: 1,
      });
      if(type == 'sku') {//sku维度
        res = await queryGoodsList(newParams);
      } else {
        res = await queryCommonGoodsList(newParams);
      }
      if (res.success) {
        const {
          data: { records },
        } = res;
        callback(records);
      } else {
        callback([]);
      }
    }
    this.timeout = setTimeout(fake, 300);
  }

  //点击展开和关闭历史记录下拉框
  handleVisibleChange = (val) => {
    const { inputVal, visible } = this.state;
    if(val) {//点击展开
      if(inputVal) {
        if(visible != 3) {
          this.setState({ visible: 3 });
        }
      } else {
        this.setState({ visible: 2 });
      }
    } else {//点击关闭
      if(inputVal) {
        return;
      } else {
        let timer = setTimeout(() => {
          clearTimeout(timer);
          timer = null;
          if(!this.inputEl.current) {
            return;
          }
          if(this.inputEl.current.input == document.activeElement) {
            return;
          } else {
            this.setState({ visible: 1 });
          }
        }, 100);
      }
    }
  }
  
  //选择下拉商品
  handleSelect = (val) => {
    const { data, goodsId } = this.state;
    const { index, type = 'sku' } = this.props;
    if(val == goodsId) {//当前点击与原选择数据相同，直接关闭下拉框
      this.setState({ visible: 1 }, () => {
        this.inputEl.current.focus();
      })
    } else {
      const obj = type == 'sku' ? find(data, [ 'goodsId', val ]) : find(data, [ 'goodsCommonid', val ]);
      this.setState({ goodsId: val, inputVal: obj.goodsName, visible: 1 }, () => {
        this.inputEl.current.focus();
        this.props.onChange && this.props.onChange(val, index, obj);
      })
    }
  }
  
  //搜索事件触发
  handleSearch = (val) => {
    if(val) {
      this.setState({ loading: true }, () => {
        this.fetch(val, (data) => {
          this.setState({ loading: false, data });
        });
      })
    }
  }
  
  //点击输入框输入事件
  handleChange = (e) => {
    const { goodsId, visible }  = this.state;
    const val = e.target.value;
    if(goodsId) {
      this.setState({ goodsId: undefined });
    }
    if(val) {
      if(visible != 3) {
        this.setState({ visible: 3, inputVal: val }, () => {
          this.handleSearch(val);
        });
      } else {
        this.setState({ inputVal: val }, () => {
          this.handleSearch(val);
        });
      }
    } else {
      this.setState({ visible: 2, data: [], inputVal: undefined });
    }
  }
  
  //输入框失焦事件
  handleBlur = () => {
    let timer = setTimeout(() => {
      clearTimeout(timer);
      timer = null;
      const { inputVal, goodsId, visible } = this.state;
      const { index } = this.props;
      if(inputVal) {
        if(!this.inputEl.current) {
          return;
        }
        if(visible == 3) {
          if(goodsId) {
            this.setState({ visible: 1 })
          } else {
            this.setState({ visible: 1, inputVal: undefined, data: [] }, () => {
              this.props.onChange && this.props.onChange(undefined, index, {});
            });
          }
        }
      } else {
        this.props.onChange && this.props.onChange(undefined, index, {});
      }
    }, 200);
  }

  render() {

    const { data, loading, visible, goodsId, inputVal } = this.state;
    const { width = '160px', storeId, type = 'sku' } = this.props;

    const options = type == 'sku' ? data.map(d => (
      <Option value={d.goodsId} key={d.goodsId} label={d.goodsName}>
        <Tooltip title={d.goodsName} >
          {d.goodsName}
        </Tooltip>
      </Option>
    )) 
    : data.map(d => (
      <Option value={d.goodsCommonid} key={d.goodsCommonid} label={d.goodsName}>
        <Tooltip title={d.goodsName} >
          {d.goodsName}
        </Tooltip>
      </Option>
    ))

    return (
      <div style={{ position: 'relative' }}>
        <Select 
          style={{ width, position: 'absolute', outline: 'none' }} 
          
          open={ visible == 3 } 
          value={ goodsId }
          onSelect={this.handleSelect}
          notFoundContent={ loading ? '加载中...' : '暂无数据' }
        >
          {options}
        </Select>
        <Popover
          title={null} 
          content={'请输入商品名称'} 
          trigger='click'
          overlayStyle={{ padding: 0, width: width, position: 'absolute' }} 
          placement="bottomLeft" 
          visible={visible == 2}
          overlayClassName="select-area-common"
          onVisibleChange={this.handleVisibleChange}
        >
          <Input 
            onBlur={this.handleBlur} 
            ref={this.inputEl} 
            value={inputVal} 
            disabled={storeId != 0 && !storeId }
            onInput={this.handleChange} 
            style={{ width: width }} 
            placeholder='请输入商品名称' 
          />
        </Popover>
      </div>
    )
  }
}


